package org.jeecg.modules.qyxx.util.pdf;


import java.awt.*;

import com.lowagie.text.Element;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.*;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;

import javax.swing.*;
import java.io.File;
import java.io.FileOutputStream;


/**
 * @author xsw
 * @ClassName: HtmlToPdf
 * @Description: TODO()
 * @date 2016-12-8 上午10:14:54
 */

public class HtmlToPdf {
    //wkhtmltopdf在系统中的路径
    private static final String toPdfTool = "D:\\tools\\wkhtmltopdf\\bin\\wkhtmltopdf.exe --javascript-delay 10000";


    /**
     * html转pdf
     *
     * @param srcPath  html路径，可以是硬盘上的路径，也可以是网络路径
     * @param destPath pdf保存路径
     * @return 转换成功返回true
     */
    public static boolean convert(String srcPath, String destPath) {
        File file = new File(destPath);
        File parent = file.getParentFile();
        //如果pdf保存路径不存在，则创建路径
        if (!parent.exists()) {
            parent.mkdirs();
        }

        StringBuilder cmd = new StringBuilder();
        /*String paramStr = "";
        paramStr = String.format("--header-html %s --header-spacing 3 ",srcPath);
        paramStr = paramStr +"--javascript-delay 10000 ";
        paramStr = paramStr + String.format("cover %s", destPath);*/
        cmd.append(toPdfTool);
        cmd.append(" ");
        cmd.append("  --header-line");//页眉下面的线
        cmd.append("  --header-center 贷后财税风险报告 ");//页眉中间内容
        // cmd.append("  --margin-top 30mm ");//设置页面上边距 (default 10mm)
        cmd.append("  --enable-javascript --debug-javascript ");//显示javascript调试输出
        // cmd.append("--javascript-delay 100000 ");
        cmd.append("  --no-stop-slow-scripts ");
        cmd.append(" --header-spacing 3 ");//    (设置页眉和内容的距离,默认0)
        //
        cmd.append(srcPath);
        // cmd.append(" --javascript-delay 10000");
        cmd.append(" ");
        cmd.append(destPath);

        boolean result = true;
        try {
            Process proc = Runtime.getRuntime().exec(cmd.toString());
            HtmlToPdfInterceptor error = new HtmlToPdfInterceptor(proc.getErrorStream());
            HtmlToPdfInterceptor output = new HtmlToPdfInterceptor(proc.getInputStream());
            error.start();
            output.start();
            proc.waitFor();
        } catch (Exception e) {
            result = false;
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) {
        HtmlToPdf.convert("http://10.10.18.244:5501/baogao.html", "d:/data/pdf/wkhtmltopdf12.pdf");
    }

    /**
     * 生成水印，加密在这里实现
     *
     * @param sourceFilePath    源文件路径
     * @param fileWaterMarkPath 水印生成文件路径
     * @throws Exception
     */
    public static void setWaterMarkForPDF(String sourceFilePath, String fileWaterMarkPath,String waterMarkName) throws Exception {
        //String waterPath = Class.class.getClass().getResource("/1.png").getPath();
        //String waterPath = "src/main/resources/templates/3607.png";
        PdfReader reader = new PdfReader(sourceFilePath);
        PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(fileWaterMarkPath));

        int total = reader.getNumberOfPages() + 1;
        // 加入水印
        PdfContentByte under = null;
        // 设置水印透明度
        PdfGState gs = new PdfGState();
        // 设置填充字体不透明度为0.2f
        gs.setFillOpacity(0.1f);
//        Image img = Image.getInstance(waterPath);
//        img.setAbsolutePosition(30, 100);//坐标
//        img.setRotation(-20);//旋转 弧度
//        img.setRotationDegrees(-35);//旋转 角度
//        img.scaleAbsolute(200, 100);//自定义大小
//        img.scalePercent(100);//依照比例缩放
        // 设置水印字体参数及大小
        BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        // LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // String waterMarkName = "中国建设银行 " + sysUser.getRealname() + "(" + sysUser.getPost() + ")";
        if (StringUtils.isBlank(waterMarkName)) {
            waterMarkName = "Tech Mahindra";
        }

        int j = waterMarkName.length();
        char c = 0;
        int rise = 0;

        // 间隔
        int interval = -5;
        // 获取水印文字的高度和宽度
        int textH = 0, textW = 0;
        JLabel label = new JLabel();
        label.setText(waterMarkName);
        FontMetrics metrics = label.getFontMetrics(label.getFont());
        textH = metrics.getHeight();
        textW = metrics.stringWidth(label.getText());


        Rectangle pageSizeWithRotation = null;

        for (int i = 1; i < total; i++)  // 每一页都加水印
        {
            rise = 500;
            under = stamp.getOverContent(i);
            // 添加图片
            //under.addImage(img);
            under.beginText();
            under.setColorFill(Color.BLACK);
            under.setFontAndSize(bf, 28);
            under.setGState(gs);

            // 获取每一页的高度、宽度
            pageSizeWithRotation = reader.getPageSizeWithRotation(i);
            float pageHeight = pageSizeWithRotation.getHeight();
            float pageWidth = pageSizeWithRotation.getWidth();
            // 根据纸张大小多次添加铺满页面， 水印文字成30度角倾斜
            for (int height = interval + textH; height < pageHeight; height = height + textH * 6) {
                for (int width = interval + textW; width < pageWidth + textW; width = width + textW * 4) {
                    under.showTextAligned(Element.ALIGN_RIGHT, waterMarkName, width + textW + 30, height - textH, 30);
                }
            }

            // 设置水印文字字体倾斜 开始
            /*if (j >= 15) {
                under.setTextMatrix(200, 120);
                for (int k = 0; k < j; k++) {
                    under.setTextRise(rise);
                    c = waterMarkName.charAt(k);
                    under.showText(c + "");
                    rise -= 20;
                }
            } else {
                under.setTextMatrix(100, 200);
                for (int k = 0; k < j; k++) {
                    under.setTextRise(rise);
                    c = waterMarkName.charAt(k);
                    under.showText(c + "");
                    rise -= 27;
                }
            }*/
            // 字体设置结束
            under.endText();
        }
        stamp.close();
        reader.close();
    }
}